package com.ea.eadp.nexus.test.pageDefinition;

import java.util.List;
import java.util.Random;

import javax.annotation.Nullable;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.ea.eadp.nexus.test.common.PageOperation;
import com.ea.eadp.nexus.test.common.TestUtil;

/**
 * User: woodywu
 */
public class Signup_Web extends BasePage {
    public static final String DEFAULTURI = baseUri + TestUtil.SignupWebConnectURI();

    public Signup_Web(WebDriver driver) {
        super(driver, Signup_Web.class);
        this.setUri(DEFAULTURI);
    }

    public void setSignupEmail(String email) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(email);
        PageOperation.SendKeyToElementAfterWait(driver, "email", email);
    }

    public boolean clickToCheckIfEmailExisted() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-splash']/div/div[2]/a/span/span")).click();
        Thread.sleep(3000);
        if (driver.findElement(By.id("panel-basic-information")).isDisplayed()) {
            return false;
        } else if (driver.findElement(By.id("panel-duplicate-email")).isDisplayed()) {
            return true;
        }
        throw new Exception("fail to check if email existed");
    }

    public void clickToSignupBasicS1() throws Exception {
        clickToSignupBasicS1(false);
    }
    
    public void clickToSignupBasicS1(boolean googleCaptcha) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-splash']/div/div[2]/a/span/span")).click();
        if (!googleCaptcha) {
            identifierId = "recaptcha_response_field";
            PageOperation.WebDriverWait(driver, identifierId);
            driver.findElement(By.id(identifierId));
        }
    }

	public void clicktoIncompleteAccount(boolean gooleCaptcha)throws Exception{
		driver.switchTo().window(this.operationWindowHandle);
		driver.findElement(By.xpath("//div[@id='panel-splash']/div/div[2]/a/span/span")).click();
		if (!gooleCaptcha) {
			identifierId = "recaptcha_response_field";
			PageOperation.WebDriverWait(driver, identifierId);
			driver.findElement(By.id(identifierId));
		}
	}

    public void clickToSignupBasicS1(String path, String regex) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-splash']/div/div[2]/a/span/span")).click();
        validatePageContent(path, regex);
    }

	public void clicktoSignupIncompleteAccount(String path,String regex)throws Exception{
		driver.switchTo().window(this.operationWindowHandle);
		driver.findElement(By.xpath("//div[@id='panel-splash']/div/div[2]/a/span/span")).click();
		validatePageContent(path, regex);
	}

    public void setOriginID(String originID) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(originID);
        PageOperation.SendKeyToElementAfterWait(driver, "originId", originID);
    }

    public String getOriginID() {
        driver.switchTo().window(this.operationWindowHandle);
        return driver.findElement(By.id("originId")).getAttribute("value");
    }

    public void setSignupPassword(String password) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(password);
        PageOperation.SendKeyToElementAfterWait(driver, "password", password);
    }

    public void setConfirmPassword(String confirmPassword) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(confirmPassword);
        PageOperation.SendKeyToElementAfterWait(driver, "confirmPassword", confirmPassword);
    }

    public void setSecurityQuestion(String question) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(question);
        String cssSelector = "#clientreg_securityqa";
        PageOperation.SelectCssDropDownItem(driver, cssSelector, question);
    }

    public void setSecurityAnswer(String answer) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(answer);
        PageOperation.SendKeyToElementAfterWait(driver, "securityAnswer", answer);
    }

    public void setDobMonth(String month) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(month);
        String cssSelector = "#clientreg_dobmonth";
        PageOperation.SelectCssDropDownItem(driver, cssSelector, month);
    }

    public void setDobDay(String day) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(day);
        String cssSelector = "#clientreg_dobday";
        PageOperation.SelectCssDropDownItem(driver, cssSelector, day);
    }

    public void setDobYear(String year) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(year);
        String cssSelector = "#clientreg_dobyear";
        PageOperation.SelectCssDropDownItem(driver, cssSelector, year);
    }

    public void setRegisterCountry(String country) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(country);
        String cssSelector = "#clientreg_country";
        PageOperation.SelectCssDropDownItem(driver, cssSelector, country);
    }

    public void setCaptcha(String value) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(value);
        PageOperation.SendKeyToElementAfterWait(driver, "recaptcha_response_field", value);
    }

    public void checkGoogleCaptcha(boolean check)
    {
        driver.switchTo().window(this.operationWindowHandle);
        String xpathOfIFrame = "//li[@id='captcha-container2']/div/div/div/iframe";
        driver.switchTo().frame(driver.findElement(By.xpath(xpathOfIFrame)));
        String xpath = "//span[@id='recaptcha-anchor']/div[5]";
        if (check && !driver.findElement(By.xpath(xpath)).isSelected()) {
            driver.findElement(By.xpath(xpath)).click();
        } else if (!check && driver.findElement(By.xpath(xpath)).isSelected()) {
            driver.findElement(By.xpath(xpath)).click();
        }
    }
    
    public void checkboxContactMe(boolean check) {
        driver.switchTo().window(this.operationWindowHandle);
        PageOperation.SelectCheckboxAfterWait(driver, "contactMe", "label-contactMe", check);
    }

    public void checkboxShareInfo(boolean check) {
        driver.switchTo().window(this.operationWindowHandle);
        PageOperation.SelectCheckboxAfterWait(driver, "shareInfo", "label-shareInfo", check);
    }

    public void checkboxReadAccept(boolean check) {
        driver.switchTo().window(this.operationWindowHandle);
        String xpath = "//li[@id='read-accept-container']/div/div/span";
        if (check && !driver.findElement(By.id("readAccept")).isSelected()) {
            driver.findElement(By.xpath(xpath)).click();
        } else if (!check && driver.findElement(By.id("readAccept")).isSelected()) {
            driver.findElement(By.xpath(xpath)).click();
        }
    }

    public void validatePageContent(String path, String regex) throws Exception {
        PageOperation.WebDriverWaitByXpath(driver, path);
        String content = driver.findElement(By.xpath(path)).getText();
        if (!content.matches(getContainsRegex(regex))) {
            throw new Exception("expected [" + regex + "] but found [" + content + "]");
        }
    }

    public void clickNextOnS1() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#submit-btn > span > span")).click();
    }

    public void clickToSignupBasicS2() throws Exception {
        clickToSignupBasicS2(false);
    }

    public void clickToSignupBasicS2(boolean googleCaptcha) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#submit-btn > span > span")).click();
        if (!googleCaptcha) {
            identifierId = "firstName";
            PageOperation.WebDriverWait(driver, identifierId);
            driver.findElement(By.id(identifierId));
        }
    }

    public void clickToSignupBasicS2(String path, String regex) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#submit-btn > span > span")).click();
        validatePageContent(path, regex);
    }

    public void setFirstName(String firstName) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(firstName);
        PageOperation.SendKeyToElementAfterWait(driver, "firstName", firstName);
    }

    public void setLastName(String lastName) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(lastName);
        PageOperation.SendKeyToElementAfterWait(driver, "lastName", lastName);
    }

    public void clickToSignupBasicS3() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-profile-settings']/div[2]/a/span/span")).click();
        PageOperation.WebDriverWaitByXpath(driver, "//div[@id='panel-profile-confirmation']/div[2]/a/span/span");
        driver.findElement(By.xpath("//div[@id='panel-profile-confirmation']/div[2]/a/span/span"));
    }

    public void clickToSignupBasicS3(String path, String regex) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-profile-settings']/div[2]/a/span/span")).click();
        validatePageContent(path, regex);
    }

    public void clickSignup() {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-profile-confirmation']/div[2]/a/span/span")).click();
    }

    public void clickToSignupComplete() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-profile-confirmation']/div[2]/a/span/span")).click();
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(new ExpectedCondition<Boolean>() {
            @Nullable
            @Override
            public Boolean apply(@Nullable WebDriver webDriver) {
                return TestUtil.getCurrentUrl(driver).contains("?code=")||TestUtil.validateTextPresent(driver,"code").contains("{\"code\":");
            }
        });
    }

    public void clickChooseAvatar() {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='profile-settings-avatar-container']/a/span/span")).click();
        PageOperation.WebDriverWait(driver, "a-uploader");
    }

    public void clickUploadImgTab() {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.id("a-uploader")).click();
        PageOperation.WebDriverWait(driver, "fileupload");
    }

    public void setImage(String file, boolean larger) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(file);
        driver.findElement(By.id("fileupload")).sendKeys(file);
        if (larger) {
            PageOperation.WebDriverWait(driver, "error-message-upload-text");
        } else {
            WebDriverWait wait = new WebDriverWait(driver, 30, 1000);
            wait.until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driver) {
                    return !driver.findElement(By.id("element-avatar-preview")).getAttribute("src").contains("/p/images/nouser.jpg");
                }
            });
            //PageOperation.WebDriverWait(driver, "element-avatar-preview");
        }
    }

    public void clickSaveAvatar() {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#button-next-crop > span > span")).click();
    }

    public String getErrorMessageByXPath(String xpath) {
        driver.switchTo().window(this.operationWindowHandle);
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return driver.findElement(By.xpath(xpath)).getText();
    }

    public void clickToSelectAvatarList() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        List<WebElement> elementList
                = driver.findElement(By.xpath("//div[@id='gallery']/div[1]/ul[1]")).findElements(By.tagName("li"));
        Random random = new Random();
        int index = random.nextInt(elementList.size());
        elementList.get(index).click();
        Thread.sleep(3000);
    }

    public void clickToSelectAvatar() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        List<WebElement> elementList
                = driver.findElement(By.xpath("//div[@id='avatar-pics']")).findElements(By.tagName("a"));
        Random random = new Random();
        int index = random.nextInt(elementList.size());
        elementList.get(index).findElement(By.tagName("img")).click();
        //PageOperation.WebDriverWait(driver, "container-gallery-avatar-preview-inner");
        Thread.sleep(3000);
        driver.findElement(By.cssSelector("#button-next-gallery > span > span")).click();
    }

    public String getMaxLength(String elementID) {
        driver.switchTo().window(this.operationWindowHandle);
        return driver.findElement(By.id(elementID)).getAttribute("maxlength");
    }

    public String getH2() {
        return getElementStringByXPath("//div[@id='panel-splash']/div[3]/h2");
    }

    public String getBannerCopy() {
        return getElementStringByXPath("//div[@id='panel-splash']/div[3]/p[1]");
    }

    public String getEmailPlaceHolder() {
        driver.switchTo().window(this.operationWindowHandle);
        return driver.findElement(By.id("email")).getAttribute("placeholder");
    }

    public String getNextBtnStringOnPreSignup() {
        return getElementStringByXPath("//div[@id='panel-splash']/div[2]/div[2]/a/span/span");
    }

    public String getBannerLoginCopy() {
        return getElementStringByXPath("//div[@id='panel-splash']/div[3]/p[2]");
    }

    public String getColHeader(int index) {
        return getElementStringByXPath("//div[@id='panel-splash']/ul/li[" + index + "]/p/strong");
    }

    public String getColCopy(int index) {
        return getElementStringByXPath("//div[@id='panel-splash']/ul/li[" + index + "]/p/span");
    }

    public String getDuplicateEmailCopy() {
        return getElementStringByXPath("//div[@id='panel-duplicate-email']/div[1]/div//p");
    }

    public String getBasicInfoHeader() {
        return getElementStringByXPath("//div[@id='panel-profile']/h1");
    }

    public String getBasicInfoH2() {
        return getElementStringByXPath("//div[@id='panel-profile']/h2");
    }

    public String getOriginIDLabel() {
        return getElementStringByXPath("//li[@id='origin-id-container']/div/label");
    }

    public String getOriginIDTip() {
        return getElementStringByXPath("//li[@id='origin-id-container']/p");
    }

    public String getPwdLabel() {
        return getElementStringByXPath("//li[@id='password-container']/div/label");
    }

    public String getPwdTip() {
        return getElementStringByXPath("//li[@id='password-container']/p");
    }

    public String getConfirmPwdLabel() {
        return getElementStringByXPath("//li[@id='confirm-password-container']/div/label");
    }

    public String getSecQuestionLabel() {
        return getElementStringByXPath("//li[@id='secquestion-container']/div/label");
    }

    public String getSecAnswerLabel() {
        return getElementStringByXPath("//li[@id='secanswer-container']/div/label");
    }

    public String getDOBLabel() {
        return getElementStringByXPath("//li[@id='dob-container']/div/div/label");
    }

    public String getCountryLabel() {
        return getElementStringByXPath("//li[@id='country-container']/div/label");
    }

    public String getSecPreferences() {
        return getElementStringByXPath("//div[@id='panel-security-preferences']/h2");
    }

    public String getCaptchaLabel() {
        return getElementStringByXPath("//li[@id='captcha-container']/div/label");
    }

    public String getContactMeLabel() {
        return getElementStringByXPath("//label[@id='label-contactMe']");
    }

    public String getShareInfoLabel() {
        return getElementStringByXPath("//label[@id='label-shareInfo']");
    }

    public String getAcceptLabel() {
        return getElementStringByXPath("//label[@id='label-readAccept']");
    }

    public String getNextBtnStringOnSignup() {
        return getElementStringByXPath("//a[@id='submit-btn']/span/span");
    }

    public String getCancelButtonString() {
        return getElementStringByXPath("//div[@id='panel-basic-information']/div[2]/a[2]/span/span");
    }

    public String getCopyRight() {
        return getElementStringByXPath("//div[@class='footer']/span");
    }

    public String getSelectedMonth() {
        return getElementStringByXPath("//div[@id='clientreg_dobmonth']/div[1]/span");
    }

    public String getSelectedDay() {
        return getElementStringByXPath("//div[@id='clientreg_dobday']/div[1]/span");
    }

    public String getSelectedYear() {
        return getElementStringByXPath("//div[@id='clientreg_dobyear']/div[1]/span");
    }

    public String getOriginIDError() throws Exception {
        return getElementStringByXPath("//li[@id='origin-id-container']/div/span[3]");
    }

    public String getPasswordError() throws Exception {
        return getElementStringByXPath("//li[@id='password-container']/div/span[3]");
    }

    public String getConfirmPwdError() throws Exception {
        return getElementStringByXPath("//li[@id='confirm-password-container']/div/span[3]");
    }

    public String getSecQuestionError() throws Exception {
        return getElementStringByXPath("//li[@id='secquestion-container']/div/span[2]");
    }

    public String getSecAnswerError() throws Exception {
        return getElementStringByXPath("//li[@id='secanswer-container']/div/span[3]");
    }

    public String getDOBError() throws Exception {
        return getElementStringByXPath("//li[@id='dob-container']/div/div/span[2]");
    }

    public void validateCaptError(String expected) throws Exception {
        validatePageContent("//li[@id='captcha-container']/div/span[3]", expected);
    }

    public String getReadAcceptError() throws Exception {
        return getElementStringByXPath("//li[@id='read-accept-container']/div/span[1]");
    }

    public String getCreateProfileHeader() throws Exception {
        return getElementStringByXPath("//div[@id='panel-profile-settings']/div[1]/div/h1");
    }

    public String getCreateProfileSettingCopy() throws Exception {
        return getElementStringByXPath("//div[@id='panel-profile-settings']/div[1]/div/p");
    }

    public String getFirstNameLabel() throws Exception {
        return getElementStringByXPath("//li[@id='name-first-container']/div[1]/label");
    }

    public String getLastNameLabel() throws Exception {
        return getElementStringByXPath("//li[@id='name-last-container']/div[1]/label");
    }

    public String getChooseAvatarButtonString() throws Exception {
        return getElementStringByXPath("//div[@id='profile-settings-avatar-container']/a/span/span");
    }

    public String getSignupButtonString() throws Exception {
        return getElementStringByXPath("//div[@id='panel-profile-settings']/div[2]/a[1]/span/span");
    }

    public String getSkipButtonString() throws Exception {
        return getElementStringByXPath("//div[@id='panel-profile-settings']/div[2]/a[2]/span/span");
    }

    public void clickSignupBasicOnCreateProfilePage() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-profile-settings']/div[2]/a/span/span")).click();
    }

    public String getFirstNameError() throws Exception {
        return getElementStringByXPath("//li[@id='name-first-container']/div/span[3]");
    }

    public String getLastNameError() throws Exception {
        return getElementStringByXPath("//li[@id='name-last-container']/div/span[3]");
    }

    public String getH2OnAvatar() {
        return getElementStringByXPath("//div[@id='panel-avatar-settings']/div[1]/div/h2");
    }

    public String getAvatarGalleryTab(){
        return getElementStringByXPath("//a[@id='a-gallery']");
    }

    public String getSaveButton(){
        return getElementStringByXPath("//a[@id='button-next-gallery']/span/span");
    }

    public String getCancelButtonOnAvatarWindow(){
        return getElementStringByXPath("//div[@id='panel-avatar-settings']/div[2]/a[1]/span/span");
    }

    public String getUploadAvatarTab() {
        return getElementStringByXPath("//a[@id='a-uploader']");
    }

    public String getFileNotice(){
        return getElementStringByXPath("//div[@id='uploader']/div[3]/span");
    }

    public String getUploadError() {
        return getErrorMessageByXPath("//div[@id='error-message-upload-text']");
    }

    public String getWelcomeHeader() {
        return getElementStringByXPath("//div[@id='panel-profile-confirmation']/div[1]/div/h1");
    }

    public String getProfileConfirmationCopy(){
        return getElementStringByXPath("//div[@id='panel-profile-confirmation']/div[1]/div/p[1]");
    }

    public String getProfileConfirmationFooterCopy(){
        return getElementStringByXPath("//div[@id='panel-profile-confirmation']/div[1]/div/p[2]");
    }

    public String getContinueButtonString(){
        return getElementStringByXPath("//div[@id='panel-profile-confirmation']/div[2]/a/span/span");
    }

    public String getContactUsTooltipString(){
        WebElement webElement = driver.findElement(By.xpath("//span[@id='contact_us']")) ;
        return webElement.getAttribute("title");
    }
    public String getAccountInfoTooltipString(){
        WebElement webElement = driver.findElement(By.xpath("//span[@id='account_info']")) ;
        return webElement.getAttribute("title");
    }
    public String getDetailsTooltipString(){
        WebElement webElement = driver.findElement(By.xpath("//span[@id='details']")) ;
        return webElement.getAttribute("title");
    }
    public String getOriginUxTooltipString(){
        WebElement webElement = driver.findElement(By.xpath("//li[@id='share-info-container']/div[1]/div/div/div/div[2]/span")) ;
        return webElement.getAttribute("innerHTML");
    }
	public void clicktoSignupIncomplete() {
		driver.switchTo().window(this.operationWindowHandle);
		driver.findElement(By.xpath("//div[@class='panel-action-area']/a[1]/span/span")).click();
		//PageOperation.WebDriverWaitByXpath(driver, "//div[@id='panel-twophase-request-confirmation']");

	}







	public String getRegFormCopyRight(){
		return getElementStringByXPath(".//*[@id='regForm']/div[7]/span");
	}



	public String getRegFormFooter(int index){
		return getElementStringByXPath(".//*[@id='regForm']/div[7]/ul/li["+index+"]/a/span");
	}


	public String getWebNewFormCopyRight(){
		return getElementStringByXPath(".//*[@id='webnewform']/div[6]/span");
	}



	public String getWebNewFormFooter(int index){
		return getElementStringByXPath(".//*[@id='webnewform']/div[6]/ul/li["+index+"]/a/span");
	}

	public String getQuestion()throws Exception{
		Thread.sleep(1000);
		driver.findElement(By.xpath(".//*[@id='clientreg_securityqa']/div[1]/span")).click();
		return getElementStringByXPath(".//*[@id='clientreg_securityqa']/div[2]/div/div/div[1]/div[2]/a/span");

	}



	public String getWebBase3CopyRight(){
		return getElementStringByXPath("html/body/div/form/div[3]/span");
	}



	public String getWebBase3Footer(int index){
		return getElementStringByXPath("//html/body/div/form/div[3]/ul/li["+index+"]/a/span");
	}

	public String getCopyRight4() {
		return getElementStringByXPath(".//*[@id='regForm']/div[7]/span");
	}

	public String getFooter5(int index) {
		return getElementStringByXPath(".//*[@id='regForm']/div[7]/ul/li["+index+"]/a/span");
	}



	public String getTwoPhaseFormRequest(){
		return getElementStringByXPath(".//*[@id='twophaseformrequest']/div[2]/span");
	}


	public String getTowPhaseFormRequestFooter(int index){
		return getElementStringByXPath(".//*[@id='twophaseformrequest']/div[2]/ul/li["+index+"]/a/span");
	}

	public String getCompleteYourAccountTitle() {
		return getElementStringByXPath(".//*[@id='link_no_error']/h1");
	}
	public String getCompleteYourAccountDescription() {
		return getElementStringByXPath(".//*[@id='link_no_error']/p");
	}

	public String getTwoPhaseRegisterTitle() {
		return getElementStringByXPath(".//*[@id='panel-twophase-request-confirmation']/div[1]/div/h1");
	}

	public String getTwoPhaseRegisterDescription() {
		return getElementStringByXPath(".//*[@id='panel-twophase-request-confirmation']/div[1]/div/p[1]");
	}
}
